package com.ecsolutions.controller;

import com.ecsolutions.service.ApplyInfo_Service;
import com.ecsolutions.soaClient.WorkFlowServiceManager;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import ta.workflow.wcf.WorkflowStub;

import java.util.Map;

/**
 * Created by Administrator on 2017/7/31.
 */
@Controller
public class ApplyInfo_Controller {
    @Autowired
    private ApplyInfo_Service applyInfo_service;
    public ApplyInfo_Service getApplyInfo_Service() {
        return applyInfo_service;
    }
    @Autowired
    private WorkFlowServiceManager workFlowServiceManager;

    @GetMapping("/applyInfo")
    public String getApplyPage(Model model,@RequestParam("loanid") String loanid,@RequestParam("userid") String userid) {

        model.addAttribute("applyInfo_info", applyInfo_service.getPopupInfo(loanid));
        model.addAttribute("userid", userid);
        model.addAttribute("loanid", loanid);

        return "applyInfo";
    }

    @PostMapping("/applyInfo")
    public String refreshApplyPage(Model model,@RequestParam("loanid") String loanid,@RequestParam("userid") String userid) {
        model.addAttribute("applyInfo_info", applyInfo_service.getPopupInfo(loanid));
        model.addAttribute("loanid", loanid);
        model.addAttribute("userid", userid);
        return "applyInfo";
    }

    @ResponseBody
    @RequestMapping(value = "/applyInfoSubmit",method = RequestMethod.POST,consumes="application/json")
    public String applyInfoSubmit(@RequestBody Map<String, String> map){

        String taskid = applyInfo_service.getWorkitemIdbyLoanid(map.get("loanid").toString());
        String workstepId = workFlowServiceManager.getCurrentTaskStepId(taskid,map.get("userid").toString());
        System.out.println(workstepId);
        String result = workFlowServiceManager.UpdateWorkItem(map.get("userid").toString(), "role1", Integer.parseInt(workstepId), 1, 4, "OK", null);
        System.out.println(result);
        JSONArray jsonArray = JSONArray.fromObject(result);
        JSONObject jsonObject = jsonArray.getJSONObject(0);
        if (jsonObject.get("isSuc").equals("true")) {
            applyInfo_service.applyInfoSubmit(map.get("userid").toString(), map.get("loanid").toString(), map.get("stepcode").toString(), map.get("result").toString());
        }
        return "success";
    }


}
